package one.stand.service.impl;

import one.stand.model.BaseModel;
import one.stand.model.CompanyCustomerLableModel;
import one.stand.model.ResultModel;
import one.stand.request.CompanyCustomerLableRequest;
import one.stand.response.CompanyCustomerLableResponse;
import one.stand.service.BaseService;
import one.stand.service.CompanyCustomerLableService;
import one.stand.service.impl.checkparam.CompanyCustomerLableServiceCheckParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 */
@Service
@Transactional
public class CompanyCustomerLableServiceImpl extends BaseService implements CompanyCustomerLableService {
    @Override
    public ResultModel<List<CompanyCustomerLableResponse>> getTree(CompanyCustomerLableRequest request) {
        CompanyCustomerLableModel model = new CompanyCustomerLableModel();
        BeanUtils.copyProperties(request, model);
        if (request.getCId() != null) {
            model.setCompanyId(request.getCId().intValue());
        }
        List<CompanyCustomerLableResponse> models = companyCustomerLableMapper.getTree(model);
        return ResultModel.success(models);
    }

    @Override
    public ResultModel<Long> addLable(CompanyCustomerLableRequest request) {
        if (CompanyCustomerLableServiceCheckParam.add(request)) {
            return ResultModel.checkParamFail();
        }
        if (request.getLableName() != null && request.getLableName().length() > 10) {
            return ResultModel.fail("标签名称不能超过10个字~！");
        }
        CompanyCustomerLableModel companyCustomerLableModel = new CompanyCustomerLableModel();
        BeanUtils.copyProperties(request, companyCustomerLableModel);
        companyCustomerLableModel.setCompanyId(request.getCId().intValue());
        companyCustomerLableModel.setUserId(request.getId().intValue());
        companyCustomerLableMapper.insertSelective(companyCustomerLableModel);
        return ResultModel.success(companyCustomerLableModel.getLableId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultModel<Boolean> addLableList(CompanyCustomerLableRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        } else if (null == request.getList()) {
            return ResultModel.checkParamFail("list为空");
        } else if (null == request.getCId()) {
            return ResultModel.checkParamFail("cId为空");
        }
        // 没有被删除的标签id集合
        List<Integer> notRemovedLabelIds = new ArrayList<>();
        try{
            recursiveValidatorAndGetLabelId(request.getList(), notRemovedLabelIds);
        } catch (IllegalArgumentException e){
            return ResultModel.fail("标签名称不能超过10个字~！");
        }
        List<CompanyCustomerLableModel> allByCompanys = companyCustomerLableMapper.findAllByCompanyId(request.getCId().intValue());

        // 删除除开保留的标签
        allByCompanys
                                  .stream()
                                  .map(CompanyCustomerLableModel::getLableId)
                                  .filter(labelId -> !notRemovedLabelIds.contains(labelId))
                                  .forEach(labelId -> companyCustomerLableMapper.deleteByPrimaryKey(new CompanyCustomerLableModel() {{
                                      setLableId(labelId);
                                      setIsDel(BaseModel.YES_DEL);
                                  }}));
        // 修改和新增标签
        recursiveSave(request.getList(), 0, request.getCId().intValue(), request.getId().intValue());

//        // 刪除标签
//        companyCustomerLableMapper.delCompanyLable(request.getCId().intValue());
//        List<CompanyCustomerLableRequest> list = request.getList();
//        for (CompanyCustomerLableRequest request1 : list) {
//            if (request.getLableName() != null && request.getLableName().length() > 10) {
//                return ResultModel.fail("标签名称不能超过10个字~！");
//            }
//            CompanyCustomerLableModel model = new CompanyCustomerLableModel();
//            model.setLableName(request1.getLableName());
//            model.setCompanyId(request.getCId().intValue());
//            model.setUserId(request.getId().intValue());
//            model.setIsDel(0);
//            model.setParentId(0);
//            if (request1.getLableId() == null) {
//                model.setCreateTime(currentDate());
//                companyCustomerLableMapper.insertSelective(model);
//            } else {
//                model.setLableId(request1.getLableId());
//                companyCustomerLableMapper.updateByPrimaryKeySelective(model);
//            }
//            for (CompanyCustomerLableRequest request2 : request1.getList()) {
//                if (request.getLableName() != null && request.getLableName().length() > 10) {
//                    return ResultModel.fail("标签名称不能超过10个字~！");
//                }
//                CompanyCustomerLableModel model1 = new CompanyCustomerLableModel();
//                model1.setLableColor(request2.getLableColor());
//                model1.setLableName(request2.getLableName());
//                model1.setCompanyId(request.getCId().intValue());
//                model1.setUserId(request.getId().intValue());
//                model1.setParentId(model.getLableId());
//                model1.setIsDel(0);
//                if (request2.getLableId() == null) {
//                    model1.setCreateTime(currentDate());
//                    companyCustomerLableMapper.insertSelective(model1);
//                } else {
//                    model1.setLableId(request2.getLableId());
//                    companyCustomerLableMapper.updateByPrimaryKeySelective(model1);
//                }
//            }
//        }
        return ResultModel.success(true);
    }

    /**
     * 循环遍历校验并获取标签id集合
     *
     * @param list  标签变更请求
     * @param labelIds 标签id集合
     */

    private void recursiveValidatorAndGetLabelId(List<CompanyCustomerLableRequest> list, List<Integer> labelIds) {
        if(list == null){
            return ;
        }
        list.stream().filter(label -> StringUtils.isNotEmpty(label.getLableName())).forEach(label -> {
            if (label.getLableName().length() > 10) {
                throw new IllegalArgumentException("标签名称不能超过10个字");
            }
            if (label.getLableId() != null) {
                labelIds.add(label.getLableId());
            }
            if (label.getList() != null) {
                recursiveValidatorAndGetLabelId(label.getList(), labelIds);
            }
        });
    }

    /**
     * 循环保存
     */
    private void recursiveSave(List<CompanyCustomerLableRequest> list, Integer parentId, Integer companyId, Integer userId){
        list.forEach(label -> {
            CompanyCustomerLableModel model = new CompanyCustomerLableModel();
            model.setLableName(label.getLableName());
            model.setCompanyId(companyId);
            model.setUserId(userId);
            model.setIsDel(0);
            model.setParentId(parentId);
            model.setLableColor(label.getLableColor());
            Integer labelId = label.getLableId();
            if(labelId == null){
                // create
                model.setCreateTime(currentDate());
                labelId = companyCustomerLableMapper.insertSelective(model);
            } else {
                // update
                companyCustomerLableMapper.updateByPrimaryKeySelective(model);
            }

            if(label.getList() != null){
                recursiveSave(label.getList(), labelId, companyId, userId);
            }
        });
    }

    @Override
    public ResultModel<Boolean> delLable(CompanyCustomerLableRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        } else if (null == request.getLableId()) {
            return ResultModel.checkParamFail("lableId为空");
        }
        CompanyCustomerLableModel inModel = companyCustomerLableMapper.selectByPrimaryKey(request.getLableId());
        if (null == inModel) {
            return ResultModel.noData();
        }
        CompanyCustomerLableModel model = new CompanyCustomerLableModel();
        if (inModel.getParentId() == null || inModel.getParentId() == 0) {
            model.setParentId(inModel.getLableId());
        }
        model.setLableId(request.getLableId());
        model.setIsDel(BaseModel.YES_DEL);
        companyCustomerLableMapper.deleteByPrimaryKey(model);
        return ResultModel.success();
    }

    @Override
    public ResultModel<Boolean> updLable(CompanyCustomerLableRequest request) {
        if (null == request) {
            return ResultModel.checkParamFail();
        } else if (null == request.getLableId()) {
            return ResultModel.checkParamFail("lableId为空");
        }
        if (request.getLableName() != null && request.getLableName().length() > 10) {
            return ResultModel.fail("标签名称不能超过10个字~！");
        }
        CompanyCustomerLableModel companyCustomerLableModel = new CompanyCustomerLableModel();
        BeanUtils.copyProperties(request, companyCustomerLableModel);
        companyCustomerLableMapper.updateByPrimaryKeySelective(companyCustomerLableModel);
        return ResultModel.success();
    }
}
